<template>
  <div class="app-container" style="position: relative; padding: 0">
    <div class="map-div" ref="mapContainer"></div>
    <div style="z-index: 2">
      <el-autocomplete style="width: 185px; position: absolute; top: 15px; left: 120px" size="small" v-model="deviceNo"
        :fetch-suggestions="querySearch" placeholder="设备检索" @select="handleSelect"></el-autocomplete>
      <div @click="showIconTypeDialog"
        style="position: absolute;right: 20px;bottom: 20px;padding: 10px 20px;font-size: 14px;color: #fff;user-select: none;cursor: pointer;border-radius: 50px;background-color: rgba(0, 0, 0, 0.6);">
        类型说明
      </div>
      <div class="view-item">
        <div @click="deviceMark2Map()">设备总量：{{ deviceList.length }}</div>
        <div style="width: 1px; background-color: #dbdbdb; margin: 0 20px"></div>
        <div style="color: #67c23a" @click="deviceMark2Map('1', null, 10)">在线：{{ onLineDeviceSize }}</div>
        <div style="width: 1px; background-color: #dbdbdb; margin: 0 20px"></div>
        <div style="color: #f56c6c" @click="deviceMark2Map('0', null, 10)">离线：{{ offLineDeviceSize }}</div>
        <div style="width: 1px; background-color: #dbdbdb; margin: 0 20px"></div>
        <div style="color: #67c23a" @click="deviceMark2Map(null, 0, 10)">空闲：{{ onLineDeviceSize - onWorkDeviceSize }}</div>
        <div style="width: 1px; background-color: #dbdbdb; margin: 0 20px"></div>
        <div style="color: #e6a23c" @click="deviceMark2Map(null, 1, 10)">工作中：{{ onWorkDeviceSize }}</div>
      </div>
    </div>
    <el-dialog top="15vh" width="600px" center title="设备类型与其对应图标" :visible.sync="iconTypeDialogShow"
      :close-on-click-modal="false" append-to-body>
      <el-table :data="iconTypeList" border style="width: 100%">
        <el-table-column prop="name" label="设备类型" width="280" align="center" />
        <el-table-column label="设备类型" align="center">
          <template slot-scope="scope">
            <el-image style="width: 24px; height: 30px" :src="scope.row.icon" :fit="'contain'"></el-image>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>

    <el-dialog top="15vh" class="device-info" width="800px" center title="设备详情" :visible.sync="infoWindowDialogVisible"
      :close-on-click-modal="false" append-to-body>
      <div>
        <el-row style="margin-bottom: 18px;">
          <el-col :span="12"><label style="padding-right: 5px;">设备名称：</label>{{ currentInfoData.name }}</el-col>
          <el-col :span="12"><label style="padding-right: 5px;">设备编号：</label>{{ currentInfoData.code }}</el-col>
        </el-row>
        <el-row style="margin-bottom: 18px;">
          <el-col :span="12"><label style="padding-right: 5px;">经度：</label>{{ currentInfoData.longitude }}</el-col>
          <el-col :span="12"><label style="padding-right: 5px;">纬度：</label>{{ currentInfoData.latitude }}</el-col>
        </el-row>
        <el-row style="margin-bottom: 18px;">
          <el-col :span="12"><label style="padding-right: 5px;">所属区域：</label>{{ currentInfoData.deptName }}</el-col>
          <el-col :span="12"><label style="padding-right: 5px;">状态：</label>{{ getStatusCN(currentInfoData.status)  }}</el-col>
        </el-row>
        <el-row style="margin-bottom: 18px;">
          <el-col :span="24"><label style="padding-right: 5px;">地址：</label>{{ currentInfoData.address }}</el-col>
        </el-row>
      </div>
    </el-dialog>
  </div>
</template>

<script>
// const mapConfig = {
//   securityJsCode: "b23c850a95afb3ca622bedf6efa527df",
//   MAPKEY: "9b855993ebffd74a39d44888fff209f7",
// };
// import AMapLoader from "@amap/amap-jsapi-loader";
import { listDevice } from "@/api/system/device";
import loadAMap from "@/utils/loadMap";
import MapContainerVue from "./MapContainer.vue";
export default {
  name: "DeviceMap",
  dicts: ['device_status'],
  components: { MapContainerVue },
  data() {
    return {
      deviceNo: "",
      deviceList: [],
      iconTypeDialogShow: false,
      iconTypeList: [],
      currentInfoData: {},
      infoWindowDialogVisible: false,
      mapMarks: [],
      locateDevices: []
    };
  },
  mounted() {
    this.getDeviceList()
    this.iconTypeList = [
      "音柱/音箱",
      "AIO报警箱",
      "融媒体客服主机",
      "网络调音台",
      "云广播适配器",
      "音频编码器",
      "村级播控主机",
      "云话筒",
      "安卓手机客户端",
      "收扩机",
      "云预警机",
      "云功放",
    ].map((it) => {
      return {
        name: it,
        icon: require("@/assets/images/device-icon.png"),
      };
    });
  },
  watch: {
    infoWindowDialogVisible(val) {
      if (!val) {
        this.currentInfoData = {}
      }
    }
  },
  computed: {
    onLineDeviceSize() {
      const result = this.deviceList.filter(it => {
        if (it.status === '1') {
          return it
        }
      }) || []
      return result.length
    },
    offLineDeviceSize() {
      const result = this.deviceList.filter(it => {
        if (it.status === '0') {
          return it
        }
      }) || []
      return result.length
    },
    onWorkDeviceSize() {
      const result = this.deviceList.filter(it => {
        if (it.playStatus === 1) {
          return it
        }
      }) || []
      return result.length
    },
    // freeTimeDeviceSize() {
    //   const result = this.deviceList.filter(it=> {
    //     if(it.playStatus === 0) {
    //       return it
    //     }
    //   }) || []
    //   return result.length
    // },
  },
  methods: {
    getStatusCN(status) {
      if(status == '1') {
        return '在线'
      } else if(status == '0') {
        return '离线'
      }
    },
    getDeviceList() {
      let params = {
        pageNum: 1,
        pageSize: 10000,
        type: 'camera',
      }
      listDevice(params).then(response => {
        this.deviceList = response.rows;
        this.initMap();
      });
    },
    showIconTypeDialog() {
      this.iconTypeDialogShow = true;
    },
    handleSelect(item) {
      console.log(item)
      this.map.setZoomAndCenter(18, [item.longitude,item.latitude]);
      const res = this.mapMarks.find(it=> {
        if(it.id === it._opts.data) {
          return it
        }
      })
      if(!res) {
        const pointer = [item.longitude, item.latitude];
        var marker = new AMap.Marker({
          // "https://webapi.amap.com/theme/v1.3/markers/n/mark_b.png"
          icon: item.status == "0"
          ? require("@/assets/images/device-icon-off.png")
          : require("@/assets/images/device-icon.png"),
          offset: new AMap.Pixel(10, -27),
          data: item,
          position: pointer,
        });
        this.mapMarks.push(marker)
        // 单独将点标记添加到地图上
        this.map.add(marker);
        marker.on("click", (e) => {
          this.currentInfoData = e.target._opts.data
          this.infoWindowDialogVisible = true
        });
      }
    },
    deviceMark2Map(status, playStatus, zoomLevel) {
      debugger;
      if (this.mapMarks && this.mapMarks.length) {
        this.mapMarks.forEach(marker => {
          this.map.remove(marker)
        })
      }
      this.mapMarks = []
      this.locateDevices.forEach((it) => {
        debugger;
        if (status && it.status !== status) {
          return false
        }
        if (playStatus && it.playStatus !== playStatus) {
          return false
        }
        const pointer = [it.longitude, it.latitude];
        var marker = new AMap.Marker({
          // "https://webapi.amap.com/theme/v1.3/markers/n/mark_b.png"
          icon: it.status == "0"
          ? require("@/assets/images/device-icon-off.png")
          : require("@/assets/images/device-icon.png"),
          offset: new AMap.Pixel(10, -27),
          data: it,
          position: pointer,
        });
        this.mapMarks.push(marker)
        // 单独将点标记添加到地图上
        this.map.add(marker);
        if (this.mapMarks.length === 1) {
          this.map.setZoomAndCenter(zoomLevel || 16, pointer);
        }
        marker.on("click", (e) => {
          console.log(e.target._opts.data)
          this.currentInfoData = e.target._opts.data
          this.infoWindowDialogVisible = true
        });
      })
    },
    querySearch(queryString, cb) {
      var deviceList = this.deviceList.map((it) =>
        Object.assign({}, it, { value: it.name, name: it.id })
      );
      var results = queryString
        ? deviceList.filter((deviceNo) => {
          return deviceNo.value.indexOf(queryString) === 0;
        })
        : deviceList;
      // 调用 callback 返回建议列表的数据
      cb(results);
    },
    async initMap() {
      this.locateDevices = this.deviceList.filter(it => {
        if (it.longitude && it.latitude) {
          return it
        }
      })
      const AMap = await loadAMap();
      this.map = new AMap.Map(this.$refs.mapContainer, {
        resizeEnable: true,
        zoom: 16, //初始化地图级别
        center: this.locateDevices.length ? [this.locateDevices[0].longitude, this.locateDevices[0].latitude] : [116.405467, 39.907761], //初始化地图中心点位置
      });
      AMap.plugin(["AMap.Scale", "AMap.ToolBar", "AMap.ControlBar"], () => {
        const Scale = new AMap.Scale();
        const toolBar = new AMap.ToolBar({
          position: "LT",
          offset: new AMap.Pixel(50, 120),
        });
        const controlBar = new AMap.ControlBar();
        // const geolocation = new AMap.Geolocation({
        //   // 是否使用高精度定位，默认：true
        //   enableHighAccuracy: true,
        //   // 设置定位超时时间，默认：无穷大
        //   timeout: 10000,
        //   // 定位按钮的停靠位置的偏移量
        //   offset: [20, 100],
        //   //  定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：false
        //   zoomToAccuracy: true,
        //   //  定位按钮的排放位置,  RB表示右下
        //   position: "RB",
        // });
        this.map.addControl(controlBar);
        this.map.addControl(toolBar);
        this.map.addControl(Scale);
      });
      setTimeout(()=>{
        this.deviceMark2Map()
      },100)
    },
  },
};
</script>

<style lang="scss" scoped>
.map-div {
  height: calc(100vh - 32px - 52px);
}

.view-item {
  user-select: none;
  color: #fff;
  font-size: 14px;
  width: auto;
  height: auto;
  background: rgba(0, 0, 0, 0.6);
  border-radius: 30px;
  padding: 10px 30px;
  position: absolute;
  left: 50%;
  top: 15px;
  transform: translate(-50%);
  height: 32px;
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  align-items: center;

  &>div {
    cursor: pointer;
  }
}

.device-info ::v-deep .el-dialog__body {
  border-top: 1px solid #dedede;
  border-bottom: 1px solid #dedede;
  overflow: auto;
  text-align: initial;
  padding: 25px 25px 30px;

}

.device-info ::v-deep .el-dialog__body .el-col {
  height: 28px;
  line-height: 28px;
}

.device-info ::v-deep .el-dialog__body .el-col label {
  width: 110px;
  width: 110px;
  display: inline-block;
  text-align: right;
}

::v-deep .amap-icon img {
  width: 32px;
}

::v-deep .map-div .amap-toolbar {
  left: 50px !important;
  top: 120px !important;
}

::v-deep .el-table td {
  padding: 6px 0;
}
</style>
